import { defineStore } from 'pinia';
import { userApi } from '@/api';
import { setToken, removeToken, setUserInfo, removeUserInfo } from '@/utils/auth';

interface UserState {
  token: string | null;
  userInfo: any | null;
  isLoggedIn: boolean;
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: localStorage.getItem('user_token'),
    userInfo: JSON.parse(localStorage.getItem('user_info') || 'null'),
    isLoggedIn: !!localStorage.getItem('user_token'),
  }),

  getters: {
    getUserInfo: (state) => state.userInfo,
    getToken: (state) => state.token,
    loggedIn: (state) => state.isLoggedIn,
  },

  actions: {
    // 登录
    async login(username: string, password: string) {
      try {
        const response = await userApi.login({ username, password });
        const { token, user } = response.data;

        // 保存token和用户信息
        this.token = token;
        this.userInfo = user;
        this.isLoggedIn = true;

        // 存储到本地
        setToken(token);
        setUserInfo(user);

        return Promise.resolve(response);
      } catch (error) {
        return Promise.reject(error);
      }
    },

    // 登出
    async logout() {
      try {
        await userApi.logout();
      } catch (error) {
        console.error('Logout error', error);
      } finally {
        // 无论请求是否成功，都清除本地数据
        this.resetState();
      }
    },

    // 获取用户信息
    async fetchUserInfo() {
      try {
        const response = await userApi.getUserInfo();
        const user = response.data;

        // 更新用户信息
        this.userInfo = user;
        setUserInfo(user);

        return Promise.resolve(user);
      } catch (error) {
        return Promise.reject(error);
      }
    },

    // 更新用户信息
    async updateUserInfo(userData: any) {
      try {
        const response = await userApi.updateUserInfo(userData);
        const updatedUser = response.data;

        // 更新用户信息
        this.userInfo = updatedUser;
        setUserInfo(updatedUser);

        return Promise.resolve(updatedUser);
      } catch (error) {
        return Promise.reject(error);
      }
    },

    // 重置状态
    resetState() {
      this.token = null;
      this.userInfo = null;
      this.isLoggedIn = false;

      // 删除本地存储
      removeToken();
      removeUserInfo();
    }
  }
}); 